/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wii.elpro.web.action;

import com.wii.elpro.dao.UserDAOInterface;
import com.wii.elpro.dao.hb.CabangDAOImpl;
import com.wii.elpro.dao.hb.DepartemenDAOImpl;
import com.wii.elpro.dao.hb.UserDAOImpl;
import com.wii.elpro.entity.User;
import com.wii.elpro.web.form.UserNewForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author hp02
 */
public class UserSaveAction extends Action {

    public UserSaveAction() {
    }

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        // MAY I DO VALIDATE password == passwordRetype IN validation.xml BY VALIDWHEN RULE
        // I'LL DO IT 
        HttpSession sess = request.getSession(true);
        User users = (User)sess.getAttribute("userSession");       
        if(users==null){
            return mapping.findForward("gagalLogin");            
        }  
        String forward;
        ActionMessages messages = null;
        UserNewForm userForm = (UserNewForm) form;
        if(new UserDAOImpl().usernameIsUsed(userForm.getUsername())) {
            //System.out.println("ALREADY USED");
            messages = new ActionMessages();
            messages.add("message", new ActionMessage("errors.usernameIsUsed"));
            saveMessages(request, messages);
            forward = "fail";
        } else {
            UserDAOInterface dao = new UserDAOImpl();
            User user = new User();
            user.setAlamat(userForm.getAlamat());
            user.setCabang(new CabangDAOImpl().getCabang(userForm.getIdCabang()));
            user.setDepartemen(new DepartemenDAOImpl().getDepartemen(userForm.getIdDepartemen()));
            user.setEmail(userForm.getEmail());
            user.setNama(userForm.getNama());
            user.setPassword(userForm.getPassword());
            user.setTelp(userForm.getTelp());
            user.setUsername(userForm.getUsername());
            try {
                dao.save(user);
                forward = "success";
            } catch (Exception e) {
                forward = "fail";
                e.printStackTrace();
            }        
        }
        return mapping.findForward(forward);
    }
}
